package com.msmap.apphome;

import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

/**
 * 谁要接收广播，谁就要自定义一个子类继承BroadCastReceiver
 */
public class MainActivity extends AppCompatActivity {

    private HeadSetReceiver headSetReceiver;
    private ScreenReceiver screenReceiver;
    private NetWorkReceiver netWorkReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //在页面加载创建的时候注册广播接收器
        //耳机插入拔出状态
        registerHeadSetReceiver();
        //屏幕状态的控制
        registerScreenReceiver();
        //网络状态
        registerNetWorkReceiver();
    }

    private void registerNetWorkReceiver() {
        netWorkReceiver = new NetWorkReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netWorkReceiver,filter);
    }

    private void registerScreenReceiver() {
        screenReceiver = new ScreenReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        // 注册动作
        registerReceiver(screenReceiver, filter);
    }

    private void registerHeadSetReceiver() {
        //步骤：
        //1.创建BroadCastReceiver对象
        headSetReceiver = new HeadSetReceiver();
        //2.创建IntentFilter对象
        IntentFilter filter = new IntentFilter();
        //3.给intentfilter注册action动作
        filter.addAction(AudioManager.ACTION_HDMI_AUDIO_PLUG);
        //4.在当前的activity上注册广播
        registerReceiver(headSetReceiver, filter);
        Log.i("aaa", "注册耳机成功！");
    }

    //销毁  的时候取消注册
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (headSetReceiver != null) {
            unregisterReceiver(headSetReceiver);
        }
        if (screenReceiver != null) {
            unregisterReceiver(screenReceiver);
        }
        if (netWorkReceiver != null) {
            unregisterReceiver(netWorkReceiver);
        }
    }
}
